package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {
       //extends ServiceImpl<WmChannelMapper, WmChannel>会默认拥有增删改查的方法
    @Override
    public ResponseResult listByName(ChannelDto dto) {
        //如果 dto 没有参数  直接返回错误提示
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR);
        }
        //Sql 查询语句
        //select * from wm_channel where name like '%?%'limit start ,size
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        //判断 获取到的dto.getName 不为空 的模糊查询
        if (StringUtils.isNotBlank(dto.getName())) {
            queryWrapper.like(WmChannel::getName, dto.getName());
        }
        //分页查询
        Page<WmChannel> page = new Page<>(dto.getPage(), dto.getSize());
        Page<WmChannel> page1 = this.page(page, queryWrapper);
        //return的参数  为  当前页码   每页条数 总条数 当前数据
        return new PageResponseResult(dto.getPage(), dto.getSize(), page1.getTotal(), page1.getRecords());
    }

    @Override
    public ResponseResult saveWmChannel(WmChannel wmChannel) {
        if (wmChannel == null || StringUtils.isBlank(wmChannel.getName())) { // 如果参数为空 返回错误信息
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //先判断这个频道在数据库中是否存在
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmChannel::getName, wmChannel.getName());
        int count = this.count(queryWrapper);
        if (count == 0) {  //代表库中无数据
            wmChannel.setCreatedTime(new Date());
            this.save(wmChannel);
            return ResponseResult.okResult();
        } else {//数据存在
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);

        }
    }
}